const { program } = require('commander');
const https = require('https');
const cheerio = require('cheerio');
const fs = require('fs');
const path = require('path');

// 配置起始期数
let f = '03001', t = '23100'
// 配置信息
let options = {
    '-f --from <dir>': {
        'description': 'start of period',
        'example': '*** -f' + f,
        'default': f,
    },
    '-t --to <dir>': {
        'description': 'end of period',
        'example': '*** -t ' + t,
        'default': t,
    },
}

function formatConfig(configs, callback) {
    Object.entries(configs).forEach(([key, val]) => {
        callback(key, val)
    })
}

formatConfig(options, (cmd, val) => {
    program.option(cmd, val.description, val.default)
})

program.parse()
const { from, to } = program.opts()

const file = path.join(__dirname, './data.json')

const ws = fs.createWriteStream(file, {
    flags: 'w',
    mode: 438,
    fd: null,
    encoding: 'utf-8'
})

const url = `https://datachart.500.com/ssq/zoushi/newinc/jbzs_redblue.php?from=${from}&to=${to}`

console.log('等待远端响应数据...');
https.get(url, (res) => {
    console.log('开始返回远端数据...');
    let htmlText = ``
    res.on('data', (d) => {
        console.log('远端数据持续获取中...');
        htmlText += d
    })
    res.on('end', () => {
        console.log('远端数据获取完成，数据处理中...');
        let data = {}
        let $ = cheerio.load(htmlText)
        $('#tdata').children('tr').not('.tdbck').each((i, elem) => {
            let period = ''
            let reds = []
            let blue = ''
            $(elem).children('[align="center"],.chartBall01,.chartBall02').each((k, ele) => {
                let num = Number($(ele).html())
                if (!isNaN(num)) {
                    if (k == 0) { // 期数
                        period = String(num)
                    } else if (k == 7) { // 蓝球
                        blue = num < 10 ? '0' + num : '' + num
                    } else { // 红球
                        reds.push(num < 10 ? '0' + num : '' + num)
                    }
                } else {
                    console.log($(ele).html() + ' Number 转换失败');
                }
            })
            data[period] = reds.join() + ' - ' + blue
        })
        console.log('远端数据处理完毕，开始写入数据...');
        console.time()
        const bf = Buffer.from(JSON.stringify(data, null, '\t'))
        ws.write(bf, ()=>{
            console.log('写入成功');
            console.timeEnd()
        })
        // fs.writeFile(file, JSON.stringify(data, null, '\t'), 'utf-8', (err) => {
        //     if (err) {
        //         console.log('数据写入失败');
        //         process.stdout.write(err)
        //         return
        //     }
        //     console.log('数据写入成功');
        //     console.timeEnd()
        // })
    })
})